package treeview.container;

import search.Visitor;
import treeview.AbstractContainer;
import treeview.NodeView;

import java.awt.*;


/**
 * Created by Pavel Nikolaev
 */
public class VerticalContainer extends AbstractContainer {

    @Override
    public void setLocation(int x, int y) {
        for (NodeView child : myNodeViews) {
            child.setLocation(x, y);
            y += child.getHeight();
        }
    }

    public void fitIntoWidth(Graphics g, int widthToFitInto) {
        myWidth = 0;
        myHeight = 0;
        for (NodeView child : myNodeViews) {
            child.fitIntoWidth(g, widthToFitInto);
            int childWidth = child.getWidth();
            if (childWidth > myWidth) myWidth = childWidth;
            myHeight += child.getHeight();
        }
        if (myWidth < widthToFitInto) setWidth(widthToFitInto);
    }

    @Override
    public void setWidth(int width) {
        if (myWidth < width) {
            for (NodeView child : myNodeViews) child.setWidth(width);
            myWidth = width;
        }
    }

    @Override
    public void setHeight(int height) {
        if (myHeight < height) {
            NodeView lastChild = getChild(countChildren() - 1);
            int lastChildHeight = lastChild.getHeight() + height - myHeight;
            lastChild.setHeight(lastChildHeight);
        }
        myHeight = height;
    }

    public void drawAt(Graphics g, int x, int y) {
        myX = x;
        myY = y;
        for (NodeView child : myNodeViews) {
            child.drawAt(g, x, y);
            y += child.getHeight();
        }
    }

    @Override
    public void accept(Visitor visitor) {
        if (visitor.visitVerticalContainer(this))
            super.accept(visitor);
    }
}
